package com.zcsy.manage.distribution.controller.system;

import java.io.File;
import java.io.FileNotFoundException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aliyun.oss.OSSClient;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.constants.DistributionConstants;
import com.zcsy.commons.constants.ShopConstants;
import com.zcsy.commons.mobile.MobileConfig;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.upload.AliyunOssUtil;
import com.zcsy.commons.upload.FileUploadUtil;
import com.zcsy.commons.upload.FileUploadUtil.UploadFileItem;
import com.zcsy.commons.util.PropertiesUtil;
import com.zcsy.manage.distribution.common.EncryptionUtil;
import com.zcsy.manage.distribution.service.base.CCommonTokenService;
import com.zcsy.manage.distribution.service.base.CICommonVerifyCodeService;
import com.zcsy.manage.distribution.service.system.IDUserService;
import com.zcsy.manage.model.base.CommonToken;
import com.zcsy.manage.model.base.CommonVerifyCode;
import com.zcsy.manage.model.system.RoleUser;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.service.sms.DlifeSmsService;
import com.zcsy.manage.service.system.IRoleService;
import com.zcsy.manage.service.system.IUserService;

/**
 * 
 * @Title:UserController
 * @Package： com.zcsy.manage.web.system
 * @Description:TODO
 * @author wangj
 * @date 2016年5月24日上午11:24:00
 * @version 1.0
 * @see JDK1.7.0_67
 * @Copyright: 2016 武汉恒数利通技术有限公司 All rights reserved.
 */

@Controller
@RequestMapping(value = "/user")
public class UserController {

	@Autowired
	private IDUserService userService;
	
	@Autowired
    private IUserService iuserService;
	
	@Autowired
	private CCommonTokenService commomTokenservice;
	
    @Autowired
    private DlifeSmsService dlifeSmsService;
    
    @Autowired
    private CICommonVerifyCodeService commonVerifyCode;
    
    @Autowired
    private IRoleService roleService;
    
    private static PropertiesUtil propertiesUtil=new PropertiesUtil("config.properties");
    private static String endpoint = propertiesUtil.getProperty("OSS_ENDPOINT");
    private static String accessId= propertiesUtil.getProperty("ACCESS_ID");
    private static String accessKey= propertiesUtil.getProperty("ACCESS_KEY");
    private static String bucketName= propertiesUtil.getProperty("bucketName");
    
	/**
	 * @Title: login
	 * @Description: 登录
	 * @param  phone 用户登录的登录名或者手机号
	 * @param  pwd 登录密码
	 * @return RequestJson
	 * @throws ParseException
	 */
	@RequestMapping(value = "userLogin")
	@ResponseBody
	public RequestJson login(String phone, String pwd, Integer userType, Integer platformType)
			throws ParseException {
		RequestJson result = new RequestJson();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("kloginname", phone);
		params.put("kpwd", pwd);
		params.put("kuserType", userType);
		
		Map<String, Object> deparams = EncryptionUtil.decrypParams(params);
		String dloginname = (String) deparams.get("kloginname");
		String dpwd = (String) deparams.get("kpwd");
		Integer duserType = (Integer) deparams.get("kuserType");
		User user = new User();
		user.setPhone(dloginname);
		user.setUserType(duserType);
		User loginUser = userService.userLogin(user);
		
		if (loginUser == null) {
			result.setSuccess(false);
			result.setResultCode(DistributionConstants.USER_NOT_EXIST);
			result.setMsg("帐号不存在！");
			
		} else if (loginUser.getPwd().equals(dpwd)) {
			
			String expire = MobileConfig.getMOBILE_TOKEN_EXPIRE();
			Integer expireInteger = Integer.valueOf(expire);
			CommonToken ct = new CommonToken();
			Date creatTime = new Date();
			ct.setCreateTime(creatTime);
			Calendar cal = Calendar.getInstance();
			cal.setTime(creatTime);
			cal.add(Calendar.MINUTE, expireInteger);
			Date expireTime = cal.getTime();
			ct.setExpireTime(expireTime);
			ct.setPlatformType(platformType);

			String token = UniqueNumberUtils.get18UniqueNumber();
			ct.setToken(token);
			String account = loginUser.getLoginname();
			if (commomTokenservice.selectByAccount(account) == null) {
				ct.setUserType(duserType);
				ct.setId(UniqueNumberUtils.get18UniqueNumber());
				ct.setAccount(account);
				commomTokenservice.insert(ct);
				
			} else {
				ct.setAccount(account);
				commomTokenservice.updateToken(ct);
				
			} 
			
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("user", loginUser);
			map.put("token", token);
			
			//根据userId获取roleId(可能为多个)
            List<RoleUser> roleIdList = roleService.getRoleIdByUserId(loginUser.getId());
            if(roleIdList == null || roleIdList.size() == 0){
            	result.setSuccess(false);
    			result.setResultCode(DistributionConstants.PASSWORD_FALSE);
    			result.setMsg("该用户没有任何权限，请联系管理员！");
    			return result;
            }
            //            Map<String,Object> roleMenuMap = new HashMap<String, Object>();
            
            Set<String> roleMenuList = null;
            
            //根据roleId获取获取roleMap(可能为多个)
            for (RoleUser item : roleIdList) {
            	List<String> roleMenu = userService.selectRoleMenu(item.getRoleId());
                //去重
                if(roleMenuList == null) {
                    roleMenuList = new HashSet<String>() ;
                }
                
                roleMenuList.addAll(roleMenu);
            }
            
            if(roleMenuList == null || roleMenuList.size() == 0){
            	result.setSuccess(false);
    			result.setResultCode(DistributionConstants.PASSWORD_FALSE);
    			result.setMsg("该用户没有任何权限，请联系管理员！");
    			return result;
            }
            
            map.put("roles", roleMenuList);
			
			result.setSuccess(true);
			result.setResultCode(DistributionConstants.LOGIN_SUCCESS);
			result.setMsg("登录成功！");
			result.setObj(map);

		} else {
			result.setSuccess(false);
			result.setResultCode(DistributionConstants.PASSWORD_FALSE);
			result.setMsg("密码错误！");
			
		}

		return result;

	}

	/**
	 * @Title: modifyInfo
	 * @Description: 修改用户信息
	 * @param  nickname 昵称
	 * @param  email 邮件
	 * @param  headimg 头像
	 * @return RequestJson
	 * @throws
	 */

	@RequestMapping(value = "modifyInfo")
	@ResponseBody
	public RequestJson modifyInfo(String nickname, String email, String headimg, String token) {
		
		RequestJson result = new RequestJson();
		Map<String, Object> params = new HashMap<String, Object>();
		//中文乱码处理
		params.put("nickname", nickname);
		params.put("email", email);
		params.put("headimg", headimg);
		params.put("tokenid", token);
		
		Map<String, Object> deparams = EncryptionUtil.decrypParams(params);
		String NICKNAME = (String) deparams.get("nickname");
		String EMAIL = (String) deparams.get("email");
		String HEADIMG = (String) deparams.get("headimg");
		String TOKEN = (String) deparams.get("tokenid");

		User user = new User();
		
		commomTokenservice.OrderInteractState(TOKEN , result);
		if (result.isSuccess()) {
			CommonToken tokenInfo = commomTokenservice.selectByToken(TOKEN);
			String loginname = tokenInfo.getAccount();
			
			if (StringUtils.isNotEmpty(NICKNAME)) {
				user.setNickname(NICKNAME);
				
			}
			if (StringUtils.isNotEmpty(EMAIL)) {
				user.setEmail(EMAIL);
			}
			if (StringUtils.isNotEmpty(HEADIMG)) {
				user.setHeadimg(HEADIMG);
				
			}
			if (StringUtils.isNotEmpty(loginname)) {
				user.setLoginname(loginname);
				
			}
			
			Date date = new Date();
			user.setModifydatetime(date);
			userService.updateInformation(user);
			
			result.setResultCode(DistributionConstants.MODIFY_INFO_SUCCESS);
		    result.setSuccess(true);
		    result.setObj(userService.selectByLoginName(loginname));
			result.setMsg("修改成功！");
			
		}
		
		return result;
	}

	/**
	* @Title: updatePwd 
	* @Description: TODO 
	* @param pwd 密码
	* @param token 会话id
	* @param opwd 密码
	* @return RequestJson
	* @author wangj 1157360454@qq.com   
	* @date 2016年6月17日 
	* @throws
	 */

	@RequestMapping(value = "updatePwd")
	@ResponseBody
	public RequestJson updatePwd(String pwd, String token,String opwd) {
		RequestJson result = new RequestJson();
		String KEY_PWD = "pwd";
		String KEY_TOKENID = "tokenid";
		String KEY_OPWD = "opwd";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put(KEY_PWD, pwd);
		params.put(KEY_TOKENID, token);
        params.put(KEY_OPWD, opwd);
        
		Map<String, Object> deparams = EncryptionUtil.decrypParams(params);
		String dpwd = (String) deparams.get(KEY_PWD);
		String dtoken = (String) deparams.get(KEY_TOKENID);
		String dopwd = (String) deparams.get(KEY_OPWD);
		
		commomTokenservice.OrderInteractState(dtoken , result);
		if (result.isSuccess()) {
			CommonToken tokenInfo = commomTokenservice.selectByToken(dtoken);
			String loginname = tokenInfo.getAccount(); 
			
			if (StringUtils.isNotEmpty(loginname)) {
				String spwd = userService.selectByLoginName(loginname).getPwd();
				
				if (spwd.equals(dopwd) && StringUtils.isNotEmpty(dpwd)) {
					Date date = new Date();
					User user = new User();
					user.setModifydatetime(date);
					user.setPwd(dpwd);
					user.setLoginname(loginname);
					userService.changePwd(user);
					
					result.setSuccess(true);
					result.setResultCode(DistributionConstants.MODIFY_PASSWORD_SUCCESS);
					result.setObj(userService.selectByLoginName(loginname));
					result.setMsg("修改成功！");
					
				} else {
                    if (spwd.equals(opwd)==false) {
						result.setSuccess(false);
						result.setMsg("输入旧密码错误！");
						result.setResultCode(DistributionConstants.OLD_PASSWORD_FALSE);
						
					}
                    if (StringUtils.isEmpty(dpwd)) {
                    	result.setSuccess(false);
						result.setMsg("新密码不能为空！");
						result.setResultCode(DistributionConstants.NEW_PASSWORD_NOT_EMPTY);
						
					}
				}
			}
			
			
		}
		
		return result;
	}

	/**
	 * @Title: lookInfo
	 * @Description: 查看个人信息
	 * @param token 会话id
	 * @return RequestJson
	 * @author wangj 1157360454@qq.com
	 * @date 2016年6月1日
	 * @throws
	 */
	@RequestMapping(value = "lookInfo")
	@ResponseBody
	public RequestJson lookInfo(String token) {
		RequestJson result = new RequestJson();
		Map<String, Object> params = new HashMap<String, Object>();
		String KEY_TOKEN = "token";
		params.put(KEY_TOKEN, token);
		
		Map<String, Object> deparams = EncryptionUtil.decrypParams(params);
		String dtoken = (String) deparams.get(KEY_TOKEN);
		commomTokenservice.OrderInteractState(dtoken , result);
		
		if (result.isSuccess()) {
			CommonToken tokenInfo = commomTokenservice.selectByToken(dtoken);
			String loginname = tokenInfo.getAccount();
			User user = userService.selectByPhone(loginname);
			
			result.setResultCode(DistributionConstants.Look_INFO_SUCCESS);
			result.setMsg("查看成功");
			result.setObj(user);
			
		}
		
		return result;
	}
	/**
	* @Title: getVerification 
	* @Description: 获取验证码 
	* @param token 会话id
	* @param phone 手机号
	* @return RequestJson
	* @author wangj 1157360454@qq.com   
	* @date 2016年6月7日 
	* @throws
	 */
	@RequestMapping(value ="getVerification",method = RequestMethod.GET)
	@ResponseBody
	public RequestJson getVerification(String phone) {
		RequestJson result = new RequestJson();
		Map<String, Object> params = new HashMap<String, Object>();
		String KEY_PHONE = "phone";
		params.put(KEY_PHONE,phone);
		
		Map<String, Object> deparams = EncryptionUtil.decrypParams(params);
		String dphone = (String) deparams.get(KEY_PHONE);
		
		List<User> userInfo = iuserService.selectUserIfPhoneExists(dphone, DistributionConstants.DISTRIBUTION_TYPE);  
		
		 if (null == userInfo) {
			result.setMsg("手机号不存在");
			result.setResultCode(DistributionConstants.PHONE_NOT_EXIST);
			result.setSuccess(false);
			
		}else {
		    //获取登录名
		    String loginname = userInfo.get(0).getLoginname();
            CommonVerifyCode code = commonVerifyCode.selectCodeByPhone(dphone);
			
			if (null != code) {
				commonVerifyCode.deleteById(code.getId());
			}
			
			Date date = new Date();
			int count =( new Random()).nextInt(999999);
			if (count<100000) {
				count+=100000;
			}
			
			String content = count+"";
			String sendtime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(date);
			Map<String,String> datas = dlifeSmsService.sendMsg(dphone, content, sendtime);
			
			String expire = MobileConfig.getVERIFYCODE_EXPIRE();
			System.out.println(expire);
			Integer expireInteger = Integer.valueOf(expire);
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			cal.add(Calendar.MINUTE, expireInteger);
			Date expireTime = cal.getTime();
			
			CommonVerifyCode verifyCode = new CommonVerifyCode();
			verifyCode.setCode(content);
			verifyCode.setCreateTime(date);
			verifyCode.setUserAccount(loginname);
			verifyCode.setId(UniqueNumberUtils.get18UniqueNumber());
			verifyCode.setExpireTime(expireTime);
			verifyCode.setPhone(dphone);
			verifyCode.setUserType(Constants.DISTRIBUTION_TYPE);
			commonVerifyCode.insert(verifyCode);
			
			result.setMsg("获取成功！");
			result.setResultCode(DistributionConstants.GET_CODE_SUCCESS);
			result.setSuccess(true);
			result.setObj(content);
			
		}
				
		return result;
	}
	
	/**
	 * 
	* @Title: boundPhone 
	* @Description: 绑定手机 
	* @param phone 手机号	
	* @param token 会话id
	* @return RequestJson
	* @author wangj 1157360454@qq.com   
	* @date 2016年6月8日 
	* @throws
	 */
	@RequestMapping(value = "boundPhone" )
	@ResponseBody
	public RequestJson boundPhone(String code , String token) {
		RequestJson result = new RequestJson();
		Map<String, Object> params = new HashMap<String, Object>();
		String KEY_TOKEN = "token";
		String KEY_PHONE = "code";
		params.put(KEY_TOKEN, token);
		params.put(KEY_PHONE, code);
		
		Map<String, Object> deparams = EncryptionUtil.decrypParams(params);
		String dtoken = (String) deparams.get(KEY_TOKEN);
		String dcode = (String) deparams.get(KEY_PHONE);
		
		commomTokenservice.OrderInteractState(dtoken , result);
		if (result.isSuccess()) {
			CommonToken tokenInfo = commomTokenservice.selectByToken(dtoken);
			String loginname = tokenInfo.getAccount();
			CommonVerifyCode verifyCode = commonVerifyCode.selectCodeByAccount(loginname);
			String codes = verifyCode.getCode();
			Date expireTime = verifyCode.getExpireTime();
			Date date = new Date();
			
			if ((date.compareTo(expireTime))<0) {
				
				if (dcode.equals(codes)) {
					result.setMsg("绑定成功！");
					result.setResultCode(DistributionConstants.PHONE_BIND_SUCCESS);
					result.setSuccess(true);
					
				}else {
					result.setMsg("输入验证码有误！");
					result.setSuccess(false);
					result.setResultCode(DistributionConstants.CODE_IS_FALSE);
					
				}
				
			}else{
				result.setMsg("验证码失效");
				result.setResultCode(DistributionConstants.CODE_IS_INVALIDE);
				result.setSuccess(false);
				
			}
				
		}
		
		return result;
	}

   /**
	* @Title: forgetPassword 
	* @Description: 忘记密码，用于重新申请密码 
	* @param token 会话id
	* @param code 验证码
	* @param pwd 密码
	* @return RequestJson
	* @author wangj 1157360454@qq.com   
	* @date 2016年6月8日 
	* @throws
	 */
	@RequestMapping(value = "forgetPassword" )
	@ResponseBody
	public RequestJson forgetPassword (String phone , String code , String pwd) {
		RequestJson result = new RequestJson();
		Map<String, Object> params = new HashMap<String, Object>();
		String KEY_PHONE = "phone";
		String KEY_CODE = "code";
		String KEY_PWD = "pwd";
		params.put(KEY_PHONE, phone);
		params.put(KEY_CODE, code);
		params.put(KEY_PWD, pwd);

		Map<String, Object> deparams = EncryptionUtil.decrypParams(params);
		String dphone = (String) deparams.get(KEY_PHONE);
		String dcode = (String) deparams.get(KEY_CODE);
		String dpwd = (String) deparams.get(KEY_PWD);

		String loginname = userService.selectLoginNameByPhone(dphone);

		if (StringUtils.isEmpty(loginname)) {
			result.setMsg("手机号未绑定帐号");
			result.setResultCode(DistributionConstants.PHONE_NOT_BIND_ACCOUNT);
			result.setSuccess(false);
			
		} else {
			CommonVerifyCode verifyCode = commonVerifyCode.selectCodeByPhone(dphone);
			String codes = verifyCode.getCode();
			Date expireTime = verifyCode.getExpireTime();
			Date date = new Date();

			if ((date.compareTo(expireTime)) < 0) {
				
				if (dcode.equals(codes)) {
					userService.forgetPass(dpwd, loginname);
					
					result.setMsg("成功操作！");
					result.setResultCode(DistributionConstants.PHONE_BIND_SUCCESS);
					result.setSuccess(true);
					

				} else {
					result.setMsg("输入验证码有误！");
					result.setSuccess(false);
					result.setResultCode(DistributionConstants.CODE_IS_FALSE);
					
				}
			} else {
				result.setMsg("验证码失效，请重新获取");
				result.setSuccess(false);
				result.setResultCode(DistributionConstants.CODE_IS_INVALIDE);
				
			}

		}
		return result;
	}
	
	
   /**
	* @Title: checkCode 
	* @Description: 校验验证码 
	* @param phone 手机号
	* @param code 验证码
	* @return RequestJson
	* @author wangj 1157360454@qq.com   
	* @date 2016年6月16日 
	* @throws
	 */
	@RequestMapping(value = "checkCode" )
	@ResponseBody
	public RequestJson checkCode (String phone , String code) {
		RequestJson result = new RequestJson();
		Map<String, Object> params = new HashMap<String, Object>();
		String KEY_PHONE = "phone";
		String KEY_CODE = "code";
		params.put(KEY_PHONE, phone);
		params.put(KEY_CODE, code);

		Map<String, Object> deparams = EncryptionUtil.decrypParams(params);
		String dphone = (String) deparams.get(KEY_PHONE);
		String dcode = (String) deparams.get(KEY_CODE);

		String loginname = userService.selectLoginNameByPhone(dphone);

		if (StringUtils.isEmpty(loginname)) {
			result.setMsg("手机号未绑定帐号");
			result.setResultCode(DistributionConstants.PHONE_NOT_BIND_ACCOUNT);
			result.setSuccess(false);
			
		} else {
			CommonVerifyCode verifyCode = commonVerifyCode.selectCodeByPhone(dphone);
			String codes = verifyCode.getCode();
			Date expireTime = verifyCode.getExpireTime();
			Date date = new Date();

			if ((date.compareTo(expireTime)) < 0) {
				
				if (dcode.equals(codes)) {
					result.setMsg("校验成功！");
					result.setResultCode(DistributionConstants.CODE_IS_INVALIDE);
					result.setSuccess(true);

				} else {
					result.setMsg("输入验证码有误！");
					result.setSuccess(false);
					result.setResultCode(DistributionConstants.CODE_IS_FALSE);
					
				}
			} else {
				result.setMsg("验证码失效，请重新获取");
				result.setSuccess(false);
				result.setResultCode(DistributionConstants.CODE_IS_INVALIDE);
				
			}

		}
		
		return result;
	}
			
	/**
     * @Description 上传头像接口 <br>
     * 1、…<br>
     * 2、…<br>
     * 
     * @param token
     * @return 
     * @author caiyinli 13277030520@163.com
     * @date 2016年7月7日
     * @see 
     */
    @RequestMapping(value = "uploadHeadPic", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson uploadHeadPic(String token,HttpServletRequest req) {

        RequestJson result = new RequestJson();
        Integer fileId = 0;

        try {
             OSSClient client = new  OSSClient(endpoint,accessId,accessKey); 
//            res.setContentType("text/html");
            final UploadFileItem[] uploadFiles = FileUploadUtil.saveUploadFile(req);

            File file = uploadFiles[0].getInternalFile();

          //图片上传至阿里云服务器
            Map<String, Object> returnmap = AliyunOssUtil.uploadFile(client,bucketName, file.getName(),file); 
            String headimgUrl = (String)returnmap.get("objectkey");
            
          //通过token获取用户信息
            CommonToken tokenInfo = commomTokenservice.selectByToken(token);
            String loginname = tokenInfo.getAccount();
            User user = userService.selectByLoginName(loginname);
            
            if(user != null){
                user.setHeadimg(headimgUrl);
                int flag = userService.updateByPrimaryKeySelective(user);
                if(flag == Constants.SQL_RESULT_SUCCESS){
                    result.setResultCode(ShopConstants.RESULT_CODE_SUCCESS);
                    result.setMsg("头像上传成功！");
                    result.setObj(user);
                }else {
                    result.setResultCode(ShopConstants.RESULT_CODE_FALSE);
                    result.setMsg("头像上传失败！");
                }
            }
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            result.setMsg("操作异常");
            result.setSuccess(false);
        }
        
        return result;
        
    }
}
